import json

from django.db import connection

from app.config import const
from app.decorator import jwt_auth
from app.service import stats, cashier_admin, operation_log, shop
from libs import common, time_helper
from libs.common import success, error
from libs.db import DB
from libs.form import RawJsonForm


@jwt_auth
def cashier_info(request, auth):
    fields = ['id', 'shop_id', 'job_num', 'username', 'status', 'created', 'updated', 'cfg']
    cashier_id = auth.get('cashier_id')
    admin = cashier_admin.get_admin(cashier_id, fields=fields)
    shop_id = admin.get('shop_id', 0)
    cfg = admin.get('cfg', '')
    try:
        cfg_obj = json.loads(cfg)
        if type(cfg_obj) is not dict:
            raise Exception('wrong config format')
    except:
        cfg_obj = {}
    admin.update({'cfg': cfg_obj})
    resp_data = {**admin}
    if shop_id != 0:
        db_shop = shop.get_shop(shop_id, ['shop_name', 'shop_phone', 'shop_address','is_fastshop'])
        resp_data.update(db_shop)
    return success(resp_data)


@jwt_auth
def handover(request, auth):
    cashier_id = auth.get('cashier_id')
    shop_id = auth.get('shop_id')
    form = RawJsonForm(request.body)
    from_time = form.get('from_time')
    to_time = form.get('to_time')
    from_ts = 0
    to_ts = 0
    if from_time != '' and to_time != '':
        from_ts = time_helper.time_str_to_ts(from_time, '%Y-%m-%d %H:%M:%S')
        to_ts = time_helper.time_str_to_ts(to_time, '%Y-%m-%d %H:%M:%S')
    db_cashier = cashier_admin.get_admin(cashier_id)
    if from_ts == 0 or to_ts == 0:
        from_ts = db_cashier.get('last_login_at')
        to_ts = common.get_ts()
    with connection.cursor() as cursor:
        # stats_result = stats.stats_order(1, 1636010932, 1636104366, cursor)
        stats_result = stats.stats_order(cashier_id, from_ts, to_ts, cursor,shop_id)
    resp_data = {
        'cashier': db_cashier,
    }
    resp_data.update(stats_result)
    return success(resp_data)


@jwt_auth
def logout(request, auth):
    with connection.cursor() as cursor:
        cashier_id = auth.get('cashier_id')
        db = DB('cs_admins', conn=cursor)
        now = common.get_ts()
        affected, _ = db.update({'last_logout_at': now}, {'id': cashier_id})
        if affected != 1:
            return error('退出失败')
        admin = db.one(['username'], {'id': cashier_id})
        log_id, err = operation_log.save({
            'typ_id': const.OPT_TYP_LOGOUT,
            'title': '退出',
            'operator_id': cashier_id,
            'operator': admin.get('username', ''),
        }, request, cursor)
        if err is not None:
            return error(err)
        elif log_id == 0:
            return error('保存退出日志异常，请重试')
    return success(last_logout_at=now)


@jwt_auth
def sign_in(request, auth):
    today_str = time_helper.date_str({'days': 0})
    today_start_ts = time_helper.time_str_to_ts(today_str)
    today_end_ts = today_start_ts + 86400
    with connection.cursor() as cursor:
        cashier_id = auth.get('cashier_id')
        db = DB('cs_opt_logs', conn=cursor)
        where = {
            'operator_id': cashier_id,
            'typ_id': const.OPT_TYP_SIGN_IN,
            'created>=%s': None,
            'created<%s': None,
        }
        binds = [today_start_ts, today_end_ts]
        num = db.count(where, binds)
        if num > 0:
            return error('今日已签到')
        db = DB('cs_admins', conn=cursor)
        admin = db.one(['username'], {'id': cashier_id})
        operation_log.save({
            'typ_id': const.OPT_TYP_SIGN_IN,
            'title': '签到',
            'operator_id': cashier_id,
            'operator': admin.get('username', ''),
        }, request, cursor)
    return success()


@jwt_auth
def is_sign_in(request, auth):
    today_str = time_helper.date_str({'days': 0})
    today_start_ts = time_helper.time_str_to_ts(today_str)
    today_end_ts = today_start_ts + 86400
    cashier_id = auth.get('cashier_id')
    with connection.cursor() as cursor:
        db = DB('cs_opt_logs', conn=cursor)
        where = {
            'operator_id': cashier_id,
            'typ_id': const.OPT_TYP_SIGN_IN,
            'created>=%s': None,
            'created<%s': None,
        }
        binds = [today_start_ts, today_end_ts]
        num = db.count(where, binds)
        sign_in_status = 0
        if num > 0:
            sign_in_status = 1
    return success(sign_in_status=sign_in_status)


@jwt_auth
def update_config(request, auth):
    cashier_id = auth.get('cashier_id')
    form = RawJsonForm(request.body)
    key = form.get('key')
    val = form.get('val')
    if key == '':
        return error('无效的配置信息')
    try:
        with connection.cursor() as cursor:
            dh = DB('cs_admins', conn=cursor)
            where = {
                'id': cashier_id
            }
            row = dh.one(['cfg'], where)
            cfg = row.get('cfg', '')
            try:
                cfg_obj = json.loads(cfg)
                if type(cfg_obj) is not dict:
                    raise Exception('wrong config format')
            except:
                cfg_obj = {}
            cfg_obj.update({key: val})
            cfg_str = json.dumps(cfg_obj)
            dh.update({'cfg': cfg_str}, where)
    except:
        pass
    return success()
